import java.util.ArrayList;
import java.util.List;

public class Solution {
    int left, right, n;
    StringBuffer path;
    List<String> ret;
    public List<String> generateParenthesis(int _n) {
        n = _n;
        path = new StringBuffer();
        ret = new ArrayList<>();

        dfs();
        return ret;
    }

    private void dfs() {
        if(right == n){
            ret.add(path.toString());
            return;
        }
        if(left < n){
            path.append('(');
            left++;
            dfs();
            path.deleteCharAt(path.length() - 1);
            left--;
        }
        if(right < left){
            path.append(')');
            right++;
            dfs();
            path.deleteCharAt(path.length() - 1);
            right--;
        }
    }
}
